﻿// ********************************
// 2010.11.24
// 拓扑信息分析
// Author:卢融凯
// ********************************
using System;
using System.Net;
using System.Linq;
using SManage.Model;
using System.Collections.Generic;

namespace SManage.Infrastructure
{
    public static class TopologyInfoAnalyst
    {
        private static SManageEntities sme;
        static TopologyInfoAnalyst() {
            sme = new SManageEntities();
        }

        public static ITopologyInfo GetFirstDeviceTopologyInfo() {
            Device firstDevice = null;
            using (var sme = new SManageEntities()) {
                var firstDevices = sme.Devices;
                if (firstDevices.Count() > 1) {
                    firstDevice = firstDevices.First();
                }
            }
            return GetTopolotyInfoFromDevice(firstDevice);
        }

        private static Device GetDeviceFromIp(IPAddress ip) {
            Device device = null;
            String targetIp = ip.ToString();
            var devices = from de in sme.Devices
                          from i in de.Mib2_ip.Mib2_ip_ipAddrEntry
                          where i.ipAdEntAddr.Trim() == targetIp
                          select de;
            if (devices.Count() > 0) {
                device = devices.First();
                device.Mib2_systemReference.Load();
                device.Mib2_ipReference.Load();
                device.Mib2_interfacesReference.Load();
                device.Mib2_interfaces.Mib2_interfaces_ifEntry.Load();
                device.Mib2_ip.Mib2_ip_ipAddrEntry.Load();
                device.Mib2_ip.Mib2_ip_ipNetToMediaEntry.Load();
                device.Mib2_ip.Mib2_ip_ipRouteEntry.Load();
            }
            return device;
        }

        public static ITopologyInfo GetTopologyInfoFromIp(IPAddress ip) {
            var device = GetDeviceFromIp(ip);
            var ti = GetTopolotyInfoFromDevice(device);
            return ti;
        }

        public static ITopologyInfo GetTopolotyInfoFromDevice(Device device) {
            if (device == null) {
                return null;
            }
            return TopologyHelper.GetStationTopologyInfo(device);
        }
    }
}
